﻿using System;
using System.Collections;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Nasa8x.Web.UI
{
    public abstract class Nasa8xControl : Panel
    {

        protected abstract void Nasa8x_Render(HtmlTextWriter output);

        
        internal Type GetWebResourceType()
        {
            //Inheritance breaks webresources
            Type controlType = GetType();

            while (controlType != typeof(Nasa8xControl))
            {
                controlType = controlType.BaseType;
            }
            return controlType;
        }

        protected override void Render(HtmlTextWriter writer)
        {

            // Render control  
            RenderCrawlerStamp(writer);
            Nasa8x_Render(writer);
            base.Render(writer);
        }



        #region RenderCrawlerStamp

        protected void RenderCrawlerStamp(HtmlTextWriter output)
        {
            Assembly thisAssembly = Assembly.GetExecutingAssembly();
            string thisAssemblyVersion = thisAssembly.GetName().Version.ToString();
            string thisProductName = GetType().ToString();


            output.RenderBeginTag(HtmlTextWriterTag.Noscript);

            output.Write(thisProductName + " " + thisAssemblyVersion);

            output.RenderEndTag(); // </noscript>
        }

        #endregion

        private static Hashtable GetRegisterHashtable()
        {
            Hashtable xControls;
            if (HttpContext.Current != null && HttpContext.Current.Items.Contains("Nasa8xScripts"))
            {
                xControls = (Hashtable)HttpContext.Current.Items["Nasa8xScripts"];
            }
            else
            {
                xControls = new Hashtable();
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Items["Nasa8xScripts"] = xControls;
                }
            }
            return xControls;
        }

        internal static bool IsClientScriptBlockRegistered(string scriptKey)
        {
            Hashtable xControls = GetRegisterHashtable();
            return xControls.Contains(scriptKey);
        }

        internal static void RegisterClientScriptBlock(string scriptKey)
        {
            Hashtable xControls = GetRegisterHashtable();
            xControls.Add(scriptKey, true);
        }
    }
}
